package com.exit66.jukebox.data;

/**
 * @author andyb
 *
 * To change this generated comment edit the template variable "typecomment":
 * Window>Preferences>Java>Templates.
 * To enable and disable the creation of type comments go to
 * Window>Preferences>Java>Code Generation.
 */

import java.io.DataOutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.exit66.jukebox.Options;
import com.exit66.jukebox.util.MediaFile;
import com.exit66.jukebox.util.XmlSegment;

public class Track extends BVDatabaseObject {
    
    private int	_trackID = -1;
    private int	_libraryID = -1;
    private String	_fileName;
    private String 	_trackName;
    private int	_albumID = -1;
    private int	_artistID = -1;
    private int	_contentTypeID = -1;
    private int	_trackNumber;
    
    private Artist  _artist = null;
    private Album   _album = null;
    private Library _library = null;
    
    public int getTrackID() {
        
        return _trackID;
        
    }
    
    public void setTrackID(int newValue) {
        
        _trackID = newValue;
        
    }
    
    public int getLibraryID() {
        
        return _libraryID;
        
    }
    
    public void setLibraryID(int newValue) {
        
        _libraryID = newValue;
        
    }
    
    public String getFileName() {
        
        return _fileName;
        
    }
    
    public String getFullFileName() {
    	Library lib = Library.getLibraryFromId(_libraryID);
    	if (lib != null) {
    		return lib.getLibraryPath() + _fileName;
    	}
    	else {
    		return "";
    	}
    }
    
    public void setFileName(String newValue) {
        
        if (newValue != null)
            _fileName = newValue;
        else
            _fileName = null;
        
    }
    
    public String getTrackName() {
        
        return _trackName;
        
    }
    
    public void setTrackName(String newValue) {
        
        if (newValue != null)
            _trackName = newValue;
        else
            _trackName = null;
        
    }
    
    public int getAlbumID() {
        
        return _albumID;
        
    }
    
    public void setAlbumID(int newValue) {
        
        _albumID = newValue;
        
    }
    
    public int getArtistID() {
        
        return _artistID;
        
    }
    
    public void setArtistID(int newValue) {
        
        _artistID = newValue;
        
    }
    
    public void setArtist(Artist artist) {
    	_artist = artist;
    }
    
    public void setAlbum(Album album) {
    	_album = album;
    }
    
    public int getContentTypeID() {
        
        return _contentTypeID;
        
    }
    
    public void setContentTypeID(int newValue) {
        
        _contentTypeID = newValue;
        
    }
    
    public int getTrackNumber() {
        
        return _trackNumber;
        
    }
    
    public void setTrackNumber(int newValue) {
        
        _trackNumber = newValue;
        
    }
    
    public Artist getArtist() {
        if ((_artist == null) || (_artistID != _artist.getArtistID())) {
            if (_artistID != -1) {
                _artist = new Artist();
                _artist.setArtistID(_artistID);
                _artist.fetch();
            } else {
                _artist = new Artist();
            }
        }
        
        return _artist;
    }
    
    public Album getAlbum() {
        if ((_album == null) || (_albumID != _album.getAlbumID())) {
            if (_albumID != -1) {
                _album = new Album();
                _album.setAlbumID(_albumID);
                _album.fetch();
            } else {
                _album = new Album();
            }
        }
        
        return _album;
    }
    
    public Library getLibrary() {
        if ((_library == null) || (_libraryID != _library.getLibraryID())) {
            if (_libraryID != -1) {
                _library = new Library();
                _library.setLibraryID(_libraryID);
                _library.fetch();
            } else {
                _library = new Library();
            }
        }
        
        return _library;
    }
    
    public boolean fetch() {
        
        if (openConnection()) {
            
            ResultSet rs = retrieveData("SELECT * FROM track WHERE track_id = " + _trackID);
            
            try {
                
                if (rs != null && rs.next()) {
                    
                    _libraryID = rs.getInt("library_id");
                    _fileName = rs.getString("file_name");
                    _trackName = rs.getString("track_name");
                    _artistID = rs.getInt("artist_id");
                    _albumID = rs.getInt("album_id");
                    _contentTypeID = rs.getInt("content_type_id");
                    _trackNumber = rs.getInt("track_number");
                    
                } else {
                    
                    _libraryID = -1;
                    _fileName = "";
                    _trackName = "";
                    _artistID = -1;
                    _albumID = -1;
                    _contentTypeID = -1;
                    _trackNumber = -1;
                    return false;
                    
                }
                
            } catch (SQLException e) {
                
                System.err.println(e);
                
            }
            
            closeConnection();
            
            return true;
            
        } else {
            
            return false;
            
        }
        
    }
    
    
    public void save() {
        
        ResultSet rs;
        
        if (openConnection()) {
            
            if (_trackID == -1) {
                
                this.find();
                
            }
            
            if (_trackID == -1) {
                
                rs = retrieveData("INSERT INTO track (library_id, file_name, track_name, artist_id, " +
                        "album_id, content_type_id, track_number, playcount) VALUES (" + _libraryID + ", " + Qts(_fileName) + ", " +
                        Qts(_trackName) + ", " + _artistID + ", " + _albumID + ", " + _contentTypeID + ", " + _trackNumber + ", 0); " +
                        "CALL IDENTITY()");
                
                try {
                    
                    if (rs.next()) {
                        
                        _trackID = rs.getInt(1);
                        
                    }
                    
                } catch (SQLException e) {
                    
                    System.err.println(e);
                    
                }
                
            } else {
                
                executeStatement("UPDATE track SET library_id = " + _libraryID + ", " +
                        "file_name = " + Qts(_fileName) + ", " +
                        "track_name = " + Qts(_trackName) + ", " +
                        "artist_id = " + _artistID + ", " +
                        "album_id = " + _albumID + ", " +
                        "content_type_id = " + _contentTypeID + ", " +
                        "track_number = " + _trackNumber +
                        " WHERE track_id = " + _trackID);
                
            }
            
            executeStatement("DELETE FROM library_failed_files WHERE library_id = " + _libraryID +
                    " AND file_name = " + Qts(_fileName));
            
            closeConnection();
            
        }
        
    }
    
    public void remove() {
        
        if (openConnection()) {
            
            executeStatement("DELETE FROM track WHERE track_id = " + _trackID);
            executeStatement("DELETE FROM playlist_track WHERE track_id = " + _trackID);
            
            closeConnection();
        }
        
    }
    
    public boolean find() {
        
        openConnection();
        
        ResultSet rs = retrieveData("SELECT track_id, track_name, artist_id, album_id, content_type_id, track_number " +
                " FROM track WHERE file_name = " + Qts(_fileName) +
                " AND library_id = " + _libraryID);
        
        try {
            
            if (rs.next()) {
                
                closeConnection();
                _trackID = rs.getInt("track_id");
                _trackName = rs.getString("track_name");
                _artistID = rs.getInt("artist_id");
                _albumID = rs.getInt("album_id");
                _contentTypeID = rs.getInt("content_type_id");
                _trackNumber = rs.getInt("track_number");
                return true;
                
            }
            
        } catch (SQLException e) {
            
            System.err.println(e);
            
        }
        
        closeConnection();
        return false;
        
    }
    
    public Properties getProperties(Properties prop) {
        
        prop.setProperty("track_id", String.valueOf(_trackID));
        prop.setProperty("library_id", String.valueOf(_libraryID));
        prop.setProperty("file_name", noNull(_fileName));
        prop.setProperty("track_name", noNull(_trackName));
        prop.setProperty("artist_id", String.valueOf(_artistID));
        prop.setProperty("album_id", String.valueOf(_albumID));
        prop.setProperty("content_type_id", String.valueOf(_contentTypeID));
        prop.setProperty("track_number", String.valueOf(_trackNumber));
        
        return prop;
        
    }
    
    public void playTrack() {
        
        openConnection();
        
        executeStatement("INSERT INTO history (track_id, entry) VALUES (" + _trackID + ", NOW())");
        
        int maxHistory = Math.max(Options.getHistoryCount(), Options.getPlaylistHistoryCount());
        
        executeStatement("DELETE FROM history WHERE track_id NOT IN (SELECT TOP " + maxHistory + " track_id FROM history ORDER BY entry DESC)");
        
        executeStatement("UPDATE track SET playcount = playcount + 1 WHERE track_id = " + _trackID);
        
        closeConnection();
    }
    
    public void getCoverImage(DataOutputStream os, boolean showNotFound) {
        
        MediaFile mf = new MediaFile(_fileName);
        mf.setLibraryID(_libraryID);
        mf.setFileName(_fileName);
        mf.getCoverImage(os, showNotFound);
        
    }
    
    public XmlSegment returnXml(boolean expandChildren) {
        return returnXml(true, true);
    }
    
    public XmlSegment returnXml(boolean expandArtist, boolean expandAlbum, XmlSegment xml) {
        xml.startNode("track");
        xml.writeNode("id", String.valueOf(_trackID));
         xml.writeNode("name", _trackName);
        xml.writeNode("number", String.valueOf(_trackNumber));
        xml.writeNode("artistId", String.valueOf(_artistID));
        if (expandArtist) {
        	xml.writeNode("artistName", getArtist().getArtistName());
        }
        xml.writeNode("albumId", String.valueOf(_albumID));
        if (expandAlbum) {
        	xml.writeNode("albumName", getAlbum().getAlbumName());
        }
        xml.writeNode("libraryId", String.valueOf(_libraryID));
        //xml.writeNode("path", getLibrary().getLibraryPath().concat(_fileName)); 
        xml.endNode("track");
        return xml;
    }
    
    public XmlSegment returnXml(boolean expandArtist, boolean expandAlbum) {
        XmlSegment xml = new XmlSegment();
        return returnXml(expandArtist, expandAlbum, xml);
    }
    
}
